package online.shiming.file.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import online.shiming.file.util.DataDo;
import online.shiming.file.util.FileUtils;
import online.shiming.file.util.FileWithProgress;

/**
 * @author ShiMing
 * @version 1.0
 * @name FileController
 * @description TODO
 * @date 2020/11/13
 */
@RequestMapping("/file/")
@RestController
@Api(value = "文件管理")
@Slf4j
public class FileController {

    @Resource
    FileWithProgress fileWithProgress;

    @PostMapping("upload")
    @ApiOperation("文件上传")
    public DataDo<?> upload(MultipartFile file, HttpServletRequest request) {
        File excelFile = null;
        try {
            excelFile = FileUtils.castToFile(file);
            if (fileWithProgress.upload(excelFile, file.getOriginalFilename(),request)) {
                return DataDo.ok("上传成功");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            FileUtils.deleteFile(excelFile);
        }
        return DataDo.error("上传失败");
    }

    @GetMapping("files")
    @ApiOperation("文件列表")
    public DataDo<?> files(String prefix) {
        return fileWithProgress.files(prefix).setCode(0);
    }

    @GetMapping("file")
    @ApiOperation("获取单个文件")
    public DataDo<?> getFile(String key) {
        return fileWithProgress.getFile(key);
    }


}
